package com.gitee.cc.common.utils;

import com.gitee.cc.dto.UserDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

/**
 * @author : cc
 * @date : Create in 14:39 2018/9/17
 */
public class ShiroUtils {
    public static Subject getSubjct()
    {
        return SecurityUtils.getSubject();
    }

    public static Session getSession()
    {
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout()
    {
        getSubjct().logout();
    }

    public static UserDTO getUser()
    {
        UserDTO user = new UserDTO();
        //TODO 为了方便测试
        if (getSubjct().getPrincipal()==null){
            UserDTO xtYh = new UserDTO();
            return xtYh;
        }else {
            BeanUtils.copyProperties(getSubjct().getPrincipal(),user );
            return user;
        }

    }

    public static void setUser(UserDTO user)
    {
        Subject subject = getSubjct();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }



    public static Long getUserId()
    {
        return getUser().getId().longValue();
    }

    public static String getLoginName()
    {
        return getUser().getUsername();
    }

    public static String getIp()
    {
        return getSubjct().getSession().getHost();
    }

    public static String getSessionId()
    {
        return String.valueOf(getSubjct().getSession().getId());
    }
}
